package com.yq.cp.service.permission.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yq.cp.config.MyException;
import com.yq.cp.config.UserThreadLocal;
import com.yq.cp.entity.basics.OrganizationalStructure;
import com.yq.cp.entity.common.ErrorCode;
import com.yq.cp.entity.common.PageVo;
import com.yq.cp.entity.permission.Role;
import com.yq.cp.entity.permission.User;
import com.yq.cp.entity.permission.UserRole;
import com.yq.cp.entity.permission.dto.UserDto;
import com.yq.cp.entity.permission.dto.UserGlrDto;

import com.yq.cp.entity.permission.vo.UserVo;
import com.yq.cp.mapper.basics.OrganizationalStructureMapper;
import com.yq.cp.mapper.permission.RoleMapper;
import com.yq.cp.mapper.permission.UserMapper;
import com.yq.cp.mapper.permission.UserRoleMapper;
import com.yq.cp.service.permission.UserService;
import com.yq.cp.utils.JwtUtil;
import com.yq.cp.utils.MD5Util;
import com.yq.cp.utils.RedisUtil;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.*;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author zh
 * @since 2022-09-21
 */
@Service
@Transactional
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {
    @Resource
    UserMapper userMapper;
    @Resource
    RoleMapper roleMapper;
    @Resource
    UserRoleMapper userRoleMapper;
    @Resource
    RedisUtil redisUtil;
    @Resource
    OrganizationalStructureMapper organizationalStructureMapper;
    @Override
    public Map<String,Object> login(User user) {
        if (user.getUsername()==null || user.getPassword()==null){
            throw new MyException(ErrorCode.USER_1101);
        }
        QueryWrapper<User> queryWrapper=new QueryWrapper<>();
        queryWrapper.eq("username",user.getUsername());
        queryWrapper.eq("password", MD5Util.encode(user.getPassword()));
        queryWrapper.eq("examine",1);
        queryWrapper.in("type",10,11,20,21);
        List<User> users = userMapper.selectList(queryWrapper);
        if (users.size()==0){
            throw new MyException(ErrorCode.USER_1102);
        }
        User u=users.get(0);
        QueryWrapper<UserRole> userRoleQueryWrapper=new QueryWrapper<>();
        userRoleQueryWrapper.eq("user_id",u.getId());
        List<UserRole> userRoles = userRoleMapper.selectList(userRoleQueryWrapper);
        if (userRoles.size()>0){
            UserRole userRole = userRoles.get(0);
            u.setRoleId(userRole.getRoleId());
        }else {

        }
        u.setCode(UUID.randomUUID().toString());
        userMapper.updateById(u);
        //获取id
        //User user2 = userMapper.selectById(user);
        if (!Objects.isNull(u.getSiteId())){
            OrganizationalStructure byId = organizationalStructureMapper.selectById(u.getSiteId());
            if (byId.getType()==6)
                u.setSitePhoto(byId.getSitePhoto());
                u.setSiteName(byId.getName());
        }


        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper.eq("phone",u.getPhone());
        wrapper.eq("nickname",u.getNickname());
        //wrapper.isNull("department_id");
        wrapper.isNotNull("site_id");
        List<User> list = userMapper.selectList(wrapper);
        if (!list.isEmpty()){
            int i = 0;
            for (User user1 : list) {
                OrganizationalStructure byId = organizationalStructureMapper.selectById(user1.getSiteId());
                if (!Objects.isNull(byId)&&byId.getType()==6){
                    i= 1;
                break;
                }
            }
            if (i==0)
                u.setSfqh(0);
            else
                u.setSfqh(1);
        }else
            u.setSfqh(0);

        if (Objects.isNull(u.getSiteId())&&Objects.isNull(u.getStructureId()))
            u.setSfqh(0);
        if (!Objects.isNull(u.getSiteId())){
            OrganizationalStructure structure = organizationalStructureMapper.selectById(u.getSiteId());
            if (!Objects.isNull(structure)&&structure.getType()!=6)
                u.setSfqh(0);
        }
        if (!Objects.isNull(u.getStructureId())){
            OrganizationalStructure structure = organizationalStructureMapper.selectById(u.getStructureId());
            if (!Objects.isNull(structure)&&structure.getType()!=6)
                u.setSfqh(0);
        }

        String token = JwtUtil.createJWT(u.getId().toString(), JSON.toJSONString(u), 1000*3600 * 24*1000);
        redisUtil.set(u.getId()+"-code",u.getCode(),24*60*60*1000);
        Map<String,Object> map=new HashMap<>();
        map.put("token",token);
        map.put("userinfo",u);
        return map;
    }

    @Override
    public Map<String,Object> getToken(User user) {
        QueryWrapper<User> queryWrapper=new QueryWrapper<>();
        queryWrapper.eq("code",user.getCode());
        User u=userMapper.selectOne(queryWrapper);
        QueryWrapper<UserRole> userRoleQueryWrapper=new QueryWrapper<>();
        userRoleQueryWrapper.eq("user_id",u.getId());
        List<UserRole> userRoles = userRoleMapper.selectList(userRoleQueryWrapper);
        if (userRoles.size()>0){
            UserRole userRole = userRoles.get(0);
            u.setRoleId(userRole.getRoleId());
        }else {

        }
        if (!Objects.isNull(u.getSiteId())){
            OrganizationalStructure byId = organizationalStructureMapper.selectById(u.getSiteId());
            if (byId.getType()==6)
                u.setSitePhoto(byId.getSitePhoto());
            u.setSiteName(byId.getName());
        }

        String token = JwtUtil.createJWT(u.getId().toString(), JSON.toJSONString(u), 1000*3600 * 24*1000);
        redisUtil.set(u.getId()+"-manage",token);
        Map<String,Object> map=new HashMap<>();
        map.put("token",token);
        map.put("userinfo",u);
        return map;
    }

    @Override
    public void add(UserVo vo) {
        if (vo.getUsername()==null || vo.getUsername()==""){
            vo.setUsername(vo.getPhone());
        }
        if (vo.getRoleId()==null){
            throw new MyException(ErrorCode.ERROR_500);
        }
        if(!this.arguments(vo)){//参数是否合法
            throw new MyException(ErrorCode.ERROR_500);
        }
        if(this.isExist(vo.getUsername(),null)){//用户名是否重复
            throw new MyException(ErrorCode.USER_1110);
        }
        Role role = roleMapper.selectById(vo.getRoleId());
        User user=new User();
        user.setUsername(vo.getUsername());
        user.setPassword(MD5Util.encode(vo.getPassword()));
        user.setPhone(vo.getPhone());
        user.setNickname(vo.getNickname());
        user.setHeadPortrait(vo.getHeadPortrait());
        user.setMailbox(vo.getMailbox());
        user.setExamine(1);
        user.setElectronicSignature(vo.getElectronicSignature());
        user.setType(role.getType());
        user.setCreateUserId(vo.getCreateUserId());
        user.setState(0);
        if (role.getType()==10 || role.getType()==11){
            user.setCompanyId(-1L);
        }
        userMapper.insert(user);

        //添加关系
        UserRole userRole=new UserRole();
        userRole.setUserId(user.getId());
        userRole.setRoleId(role.getId());
        userRole.setCreateUserId(vo.getCreateUserId());
        userRoleMapper.insert(userRole);
    }






    @Override
    public List<UserGlrDto> byPhone(String phone) {
        QueryWrapper<User> queryWrapper=new QueryWrapper<>();
        queryWrapper.eq("phone",phone);
        queryWrapper.in("type",20,21);
        List<User> users = userMapper.selectList(queryWrapper);
        List<UserGlrDto> list=new ArrayList<>();
        for (int i = 0; i < users.size(); i++) {
            User user = users.get(i);
            UserGlrDto dto=new UserGlrDto();
            String token = JwtUtil.createJWT(user.getId().toString(), JSON.toJSONString(user), 1000*3600 * 24*1000);
            dto.setToken(token);
            if (user.getType()==20){
                dto.setName("管理员");
            }else {
                dto.setName("投资人");
            }
            list.add(dto);
        }
        return list;
    }

    @Override
    public void updatePassword(UserVo vo) {

        User u = userMapper.byId(vo.getId());
        if (u!=null){
            String encode = MD5Util.encode(vo.getPassword());
            String password = MD5Util.encode(vo.getNewPassword());
            if (!encode.equals(u.getPassword())){
                throw new MyException("旧密码错误");
            }
            u.setPassword(password);
            userMapper.updateById(u);
        }
    }

    @Override
    public void update(UserVo vo) {
        if (vo.getUsername()==null || vo.getUsername()==""){
            vo.setUsername(vo.getPhone());
        }

        if (vo.getRoleId() == null) {
            throw new MyException(ErrorCode.ERROR_500);
        }
        if(!this.arguments(vo)){//参数是否合法
            throw new MyException(ErrorCode.ERROR_500);
        }
        if(this.isExist(vo.getUsername(),vo.getId())){//用户名是否重复
            throw new MyException(ErrorCode.USER_1110);
        }
        Role role = roleMapper.selectById(vo.getRoleId());
        if (role==null){
            throw new MyException(ErrorCode.role_1201);
        }
        User user = userMapper.selectById(vo.getId());
        user.setUsername(vo.getUsername());
        if (vo.getPassword()!=null && !vo.getPassword().equals("")){
            user.setPassword(MD5Util.encode(vo.getPassword()));
        }

        user.setPhone(vo.getPhone());
        user.setNickname(vo.getNickname());
        user.setHeadPortrait(vo.getHeadPortrait());
        user.setMailbox(vo.getMailbox());
        user.setType(role.getType());
        userMapper.updateById(user);

        //删除关系
        userRoleMapper.deleteByUserId(user.getId());
        //添加关系
        UserRole userRole=new UserRole();
        userRole.setUserId(user.getId());
        userRole.setRoleId(role.getId());
        userRole.setCreateUserId(vo.getCreateUserId());
        userRoleMapper.insert(userRole);
    }

    @Override
    public void delete(UserVo userVo) {
        //删除关系
        userRoleMapper.deleteByUserId(userVo.getId());
//        User user = userMapper.selectById(userVo.getId());
//        user.setType(30);
        userMapper.deleteById(userVo.getId());
    }

    @Override
    public void updateState(UserVo userVo) {

        User user = userMapper.selectById(userVo.getId());
        user.setState(userVo.getState());
        userMapper.updateById(user);
    }



    @Override
    public UserDto byId(Long id) {
        UserVo userVo=new UserVo();
        userVo.setId(id);
        IPage<UserDto> iPage= new Page<>(0, 1);
        IPage<UserDto> page = userMapper.page(iPage, userVo);
        return page.getRecords().get(0);
    }


    //账号是否重复
    private boolean isExist(String username,Long id){
        QueryWrapper<User> queryWrapper=new QueryWrapper<>();
        queryWrapper.eq("username",username);
        queryWrapper.in("type",10,11,20,21);
        if (id!=null){
            queryWrapper.notIn("id",id);
        }
        long count = userMapper.selectCount(queryWrapper);
        if (count>0){
            return true;
        }
        return false;
    }
    //参数是否合法
    private boolean arguments(UserVo user){
        if (user.getUsername()==null || user.getUsername()==null ){
            return false;
        }
//        if (user.getPassword().equals("") || user.getPassword().equals("")){
//            return false;
//        }
        if (user.getPhone().equals("") || user.getPhone().equals("")){
            return false;
        }
        return true;
    }


    @Override
    public Map<String, Object> cut() {
        User user = UserThreadLocal.get();
        String phone = user.getPhone();
        QueryWrapper<User> queryWrapper=new QueryWrapper<>();
        queryWrapper.eq("phone",phone);
        if (user.getType()==30){
            queryWrapper.in("type",20,21);
        }else {
            queryWrapper.eq("type",30);
        }

        User u = userMapper.selectOne(queryWrapper);
        if (u==null){
            throw new MyException("切换身份失败,为查询到用户信息");
        }

        String token = JwtUtil.createJWT(u.getId().toString(), JSON.toJSONString(u), 1000*3600 * 24*1000);
        Map<String,Object> map=new HashMap<>();
        map.put("token",token);
        map.put("userinfo",u);
        return map;
    }

    @Override
    public IPage<User> structureList(PageVo vo) {
        Page<User> page = new Page<>(vo.getPage(), vo.getSize());
        page = userMapper.structureList(page,vo);
        return page;
    }

    @Override
    public void addStructure(UserVo vo) {
        if (vo.getUsername()==null || vo.getUsername()==""){
            vo.setUsername(vo.getPhone());
        }
        vo.setRoleId(vo.getPositionId());
        if (vo.getRoleId()==null){
            throw new MyException(ErrorCode.ERROR_500);
        }
        if(!this.arguments(vo)){//参数是否合法
            throw new MyException(ErrorCode.ERROR_500);
        }
        if(Objects.isNull(vo.getId())&&this.isExist(vo.getUsername(),null)){//用户名是否重复
            throw new MyException(ErrorCode.USER_1110);
        }
        Role role = roleMapper.selectById(vo.getRoleId());

//        if (role.getType()==10 || role.getType()==11){
//            user.setCompanyId(-1L);
//        }
        if (Objects.isNull(vo.getId())) {
            User user = new User();
            user.setUsername(vo.getUsername());
            if (!Objects.isNull(vo.getPassword()))
                user.setPassword(MD5Util.encode(vo.getPassword()));
            user.setPhone(vo.getPhone());
            user.setNickname(vo.getNickname());
            user.setHeadPortrait(vo.getHeadPortrait());
            user.setMailbox(vo.getMailbox());
            user.setType(11);
            user.setSiteId(vo.getSiteId());
            user.setDepartmentId(vo.getDepartmentId());
            user.setPositionId(vo.getPositionId());
            if (!Objects.isNull(vo.getElectronicSignature()))
                user.setElectronicSignature(vo.getElectronicSignature());
            user.setCreateUserId(vo.getCreateUserId());
            user.setState(0);
            user.setExamine(1);
            userMapper.insert(user);
            //添加关系
            UserRole userRole=new UserRole();
            userRole.setUserId(user.getId());
            userRole.setRoleId(vo.getPositionId());
            userRole.setCreateUserId(vo.getCreateUserId());
            userRoleMapper.insert(userRole);
        }
        if (!Objects.isNull(vo.getId())){
            User user = userMapper.selectById(vo.getId());
            user.setUsername(vo.getUsername());
            if (!Objects.isNull(vo.getPassword())&&!"".equals(vo.getPassword()))
                user.setPassword(MD5Util.encode(vo.getPassword()));
            user.setPhone(vo.getPhone());
            user.setNickname(vo.getNickname());
            user.setHeadPortrait(vo.getHeadPortrait());
            user.setMailbox(vo.getMailbox());
            user.setType(11);
            user.setSiteId(vo.getSiteId());
            user.setDepartmentId(vo.getDepartmentId());
            user.setPositionId(vo.getPositionId());
            if (!Objects.isNull(vo.getElectronicSignature()))
                user.setElectronicSignature(vo.getElectronicSignature());
            user.setCreateUserId(vo.getCreateUserId());
            user.setState(0);
            user.setExamine(1);
            userRoleMapper.deleteByUserId(user.getId());
            //添加关系
            UserRole userRole=new UserRole();
            userRole.setUserId(user.getId());
            userRole.setRoleId(vo.getPositionId());
            userRole.setCreateUserId(vo.getCreateUserId());
            userRoleMapper.insert(userRole);
            userMapper.updateById(user);
        }

    }

    @Override
    public void siteHeaderAdd(UserVo vo) {
        vo.setRoleId(3L);
        if (vo.getUsername()==null || vo.getUsername()==""){
            vo.setUsername(vo.getPhone());
        }
        if (vo.getRoleId()==null){
            throw new MyException(ErrorCode.ERROR_500);
        }
        if(!this.arguments(vo)){//参数是否合法
            throw new MyException(ErrorCode.ERROR_500);
        }
        if(this.isExist(vo.getUsername(),null)){//用户名是否重复
            throw new MyException(ErrorCode.USER_1110);
        }
        Role role = roleMapper.selectById(vo.getRoleId());
        User user=new User();
        user.setUsername(vo.getUsername());
        user.setPassword(MD5Util.encode(vo.getPassword()));
        user.setPhone(vo.getPhone());
        user.setNickname(vo.getNickname());
        user.setHeadPortrait(vo.getHeadPortrait());
        user.setMailbox(vo.getMailbox());
        user.setType(role.getType());
        user.setCreateUserId(vo.getCreateUserId());
        user.setStructureId(vo.getSiteId());
        user.setSiteId(vo.getSiteId());
        user.setElectronicSignature(vo.getElectronicSignature());
        user.setSiteName(vo.getSiteName());
        user.setState(0);
        user.setExamine(0);
//        if (role.getType()==10 || role.getType()==11){
//            user.setCompanyId(-1L);
//        }
        userMapper.insert(user);

        //添加关系
        UserRole userRole=new UserRole();
        userRole.setUserId(user.getId());
        userRole.setRoleId(role.getId());
        userRole.setCreateUserId(vo.getCreateUserId());
        userRoleMapper.insert(userRole);
    }

    @Override
    public void siteHeaderUpdate(UserVo vo) {
        vo.setRoleId(3L);
        if (vo.getUsername()==null || vo.getUsername()==""){
            vo.setUsername(vo.getPhone());
        }

        if (vo.getRoleId() == null) {
            throw new MyException(ErrorCode.ERROR_500);
        }
        if(!this.arguments(vo)){//参数是否合法
            throw new MyException(ErrorCode.ERROR_500);
        }
//        if(this.isExist(vo.getUsername(),vo.getId())){//用户名是否重复
//            throw new MyException(ErrorCode.USER_1110);
//        }
        Role role = roleMapper.selectById(vo.getRoleId());
        if (role==null){
            throw new MyException(ErrorCode.role_1201);
        }
        User user = userMapper.selectById(vo.getId());
        user.setUsername(vo.getUsername());
        if (vo.getPassword()!=null && !vo.getPassword().equals("")){
            user.setPassword(MD5Util.encode(vo.getPassword()));
        }

        user.setPhone(vo.getPhone());
        user.setNickname(vo.getNickname());
        user.setHeadPortrait(vo.getHeadPortrait());
        user.setMailbox(vo.getMailbox());
        user.setType(role.getType());
        user.setElectronicSignature(vo.getElectronicSignature());
        user.setStructureId(vo.getSiteId());
        user.setState(0);
        if (!Objects.isNull(vo.getExamine()))
            user.setExamine(0);
        userMapper.updateById(user);

        //删除关系
        userRoleMapper.deleteByUserId(user.getId());
        //添加关系
        UserRole userRole=new UserRole();
        userRole.setUserId(user.getId());
        userRole.setRoleId(role.getId());
        userRole.setCreateUserId(vo.getCreateUserId());
        userRoleMapper.insert(userRole);
    }

    @Override
    public String getCode() {
        User user = userMapper.selectById(UserThreadLocal.get().getId());
        String code = UUID.randomUUID().toString();
        user.setCode(code);
        userMapper.updateById(user);
        return code;
    }

    @Override
    public User cxuser(Long id) {
        User cxuser = userMapper.cxuser(id);
        return cxuser;
    }

    @Override
    public IPage<UserDto> page(UserVo userVo) {
        IPage<UserDto> iPage= new Page<>(userVo.getPage(), userVo.getSize());
        IPage<UserDto> page = userMapper.page(iPage, userVo);
        return page;
    }
}
